package com.xia.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xia.pojo.Lend;
import com.xia.pojo.Reader;
import com.xia.service.BookService;
import com.xia.service.LendService;
import com.xia.utils.AjaxUtils;
import com.xia.utils.Const;
import com.xia.utils.PageBean;
import com.xia.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/lend")
public class LendInfoController {

    @Autowired
    public LendService lendService;

    @Autowired
    public BookService bookService;

    @RequestMapping("/toLendList")
    public String toLendList(HttpSession session) {
        if (session.getAttribute(Const.ADMIN) != null) {
            return "listDisBackAdmin";
        }
        if (session.getAttribute(Const.READER) != null) {
            return "listDisBackReader";
        }
        return "login";
    }

    @PostMapping("/lendList")
    @ResponseBody
    public String lendQueryPage(@RequestParam(value = "page", defaultValue = "1") Integer pageNo,
                                @RequestParam(value = "limit", defaultValue = "5") Integer pageSize,
                                String readerName, String bookName, String state, HttpSession session) {

        // 获取当前登录的用户
        Reader currentReader = (Reader) session.getAttribute(Const.READER);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("pageNo", pageNo);
        paramMap.put("pageSize", pageSize);
        if (currentReader != null) {
            paramMap.put("readerId", currentReader.getReaderId());
        }
        // 检索条件
        if (StringUtil.isNotEmpty(readerName)) {
            paramMap.put("readerName", readerName.trim());
        }
        if (StringUtil.isNotEmpty(bookName)) {
            paramMap.put("bookName", bookName.trim());
        }
        if (StringUtil.isNotEmpty(state)) {
            paramMap.put("state", state.trim());
        }

        ObjectMapper mapper = new ObjectMapper();
        PageBean<Lend> lendPageBean;
        Map<String, Object> resultMap = new HashMap<>();
        try {
            lendPageBean = lendService.lendQueryPage(paramMap);
            resultMap.put("code", 0);
            resultMap.put("msg", "OK");
            resultMap.put("count", lendPageBean.getTotalSize());
            resultMap.put("data", lendPageBean);
            return mapper.writeValueAsString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("msg", "NG！！！");
            resultMap.put("data", null);
            resultMap.put("count", 0);
            try {
                return mapper.writeValueAsString(resultMap);
            } catch (Exception ex) {
                ex.printStackTrace();
                return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
            }
        }
    }

    @PostMapping("/backBook")
    @ResponseBody
    public String backBook(Integer id) {

        AjaxUtils ajaxUtils = new AjaxUtils();
        try {
            lendService.backBook(id);
            ajaxUtils.setCode(0);
            ajaxUtils.setStatus("0");
            ajaxUtils.setMessage("归还成功");
            ajaxUtils.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setMessage("归还失败");
            ajaxUtils.setSuccess(false);
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxUtils);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }

    @PostMapping("/lendBook")
    @ResponseBody
    public String lendBook(Integer bookId, Integer stock, HttpSession session) {

        AjaxUtils ajaxUtils = new AjaxUtils();
        // 获取当前登录的读者用户
        Reader currentReader = (Reader) session.getAttribute(Const.READER);
        // 读者id
        Integer readerId = currentReader.getReaderId().intValue();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("readerId", readerId);
        paramMap.put("bookId", bookId);
        // 借阅之前，先判断库存是否够用
        if (stock <= 0) {
            ajaxUtils.setMessage("库存不够");
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setSuccess(false);
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.writeValueAsString(ajaxUtils);
            } catch (Exception e) {
                e.printStackTrace();
                return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
            }
        }
        // 再判断该用户是否已经借用未还该书籍
        Integer count = lendService.checkCanLen(paramMap);
        if (count > 0) {
            ajaxUtils.setMessage("您已经借阅了该书籍！");
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setSuccess(false);
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.writeValueAsString(ajaxUtils);
            } catch (Exception e) {
                e.printStackTrace();
                return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
            }
        }
        // 判断用户所借书籍数量是否达到上限
        paramMap.put("bookId", null);
        // 已经借出的书籍的数量
        Integer countSize = lendService.checkCanLen(paramMap);
        // 用户可借的上限数量
        Integer cardState = currentReader.getCardState();
        if (cardState < countSize + 1) {
            ajaxUtils.setMessage("借出书籍数量到达上限！");
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setSuccess(false);
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.writeValueAsString(ajaxUtils);
            } catch (Exception e) {
                e.printStackTrace();
                return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
            }
        }

        // 满足以上条件，则可以借阅
        paramMap.put("bookId", bookId);
        try {
            lendService.lendBook(paramMap);
            ajaxUtils.setMessage("借阅成功！");
            ajaxUtils.setCode(0);
            ajaxUtils.setStatus("0");
            ajaxUtils.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxUtils.setMessage("系统异常！");
            ajaxUtils.setCode(3);
            ajaxUtils.setStatus("3");
            ajaxUtils.setSuccess(false);
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxUtils);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }
}